package com.alibaba.algo.apiimpl.feign;

import cn.hutool.core.map.MapUtil;
import com.alibaba.algo.apiimpl.user.SysUserCacheServiceImpl;
import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.feign.service.GroupFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.*;
import com.alibaba.algo.cooperation.feign.vo.res.GroupBaseInfoResponseVO;
import com.alibaba.algo.cooperation.feign.vo.res.XbomGroupEmpResVO;
import com.alibaba.algo.cooperation.feign.vo.res.XbomGroupInfoResVO;
import com.alibaba.algo.cooperation.usercenter.GlobalResultStatus;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.*;
import com.alibaba.algo.core.base.PagerEntity;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.domain.user.*;
import com.alibaba.algo.dtos.user.EmployeeUserOrgDTO;
import com.alibaba.algo.entity.user.SysEmployee;
import com.alibaba.algo.entity.user.SysEmployeeGroup;
import com.alibaba.algo.entity.user.SysGroup;
import com.alibaba.algo.entity.user.SysOrg;
import com.alibaba.algo.entity.user.SysOrgGroup;
import com.alibaba.algo.entity.user.SysUser;
import com.alibaba.algo.enums.SysGroupStateEnum;
import com.alibaba.algo.excellistener.SysGroupListener;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.exception.SysGroupErrorCode;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.algo.utils.UserContextUtils;
import com.alibaba.excel.EasyExcel;
import com.xxl.sso.core.user.XxlSsoUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类SysGroupServiceImpl.java的实现描述：用户组 serviceimpl
 *
 * @author fan.tianpeng 2021-05-06 19:30:27
 */
@Slf4j
@RestController
public class GroupFeignServiceImpl implements GroupFeignService {

    @Autowired
    private SysGroupDomain sysGroupDomain;

    @Autowired
    private SysEmployeeGroupDomain sysEmployeeGroupDomain;

    @Autowired
    private SysOrgGroupDomain sysOrgGroupDomain;

    @Autowired
    private SysUserDomain sysUserDomain;

    @Autowired
    private SysOrgDomain sysOrgDomain;

    @Autowired
    private SysEmployeeOrgDomain sysEmployeeOrgDomain;

    @Autowired
    private SysUserCacheServiceImpl sysUserCacheService;

    @Resource
    private SysEmployeeDomain sysEmployeeDomain;

    /**
     * 用户组分页查询
     *
     * @param vo 入参
     * @return 分页结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<PagerEntity<SelectGroupPageResponseVO>> selectPage(SelectGroupPageRequestVO vo) {
        int pageIndex = vo.getPageIndex();
        if (pageIndex < 0) {
            throw new BaseException(BaseErrorCode.PAGE_INDEX_IS_NULL.getCode(), BaseErrorCode.PAGE_INDEX_IS_NULL.getMessage());
        }
        int pageSize = vo.getPageSize();
        if (pageSize <= 0) {
            throw new BaseException(BaseErrorCode.PAGE_SIZE_IS_NULL.getCode(), BaseErrorCode.PAGE_SIZE_IS_NULL.getMessage());
        }
//        Set<Long> groupIdSet = sysGroupDomain.getGroupIdSetByEmployeeCondition(vo);
        SysGroup sysGroup = new SysGroup();
        BeanUtils.copyProperties(vo, sysGroup);
//        sysGroup.setGroupIdList(new ArrayList<>(groupIdSet));
        PagerEntity<SelectGroupPageResponseVO> result = pageSelect(sysGroup, pageIndex, pageSize);
        return BaseResult.buildSuccess(result);
    }

    private PagerEntity<SelectGroupPageResponseVO> pageSelect(SysGroup sysGroup, Integer pageIndex, Integer pageSize) {
        PagerEntity<SelectGroupPageResponseVO> result = new PagerEntity<>();
        PagerEntity<SysGroup> groupPager = sysGroupDomain.pageByParaWithEmployeeCondition(sysGroup, pageIndex, pageSize, null);
        List<SysGroup> sysGroupList = groupPager.getDataList();
        result.setTotal(groupPager.getTotal());
        result.setTotalPages(groupPager.getTotalPages());
        // 如果无数据,直接返回
        if (CollectionUtils.isEmpty(sysGroupList)) {
            return result;
        }
        List<SelectGroupPageResponseVO> resList = new ArrayList<>();
        // 遍历赋值
        Collections.synchronizedCollection(sysGroupList).parallelStream().forEach(s -> {
            SelectGroupPageResponseVO responseVO = new SelectGroupPageResponseVO();
            BeanUtils.copyProperties(s, responseVO);
            // 处理时间
            responseVO.setGmtCreated(this.convertLocalDateTime(s.getGmtCreated()));
            responseVO.setGmtModified(this.convertLocalDateTime(s.getGmtModified()));
            //根据用户组查询员工
            List<EmployeeInfo> employeeInfoList = new ArrayList<>();
            if (null != s.getId() && s.getId() > 0) {
                employeeInfoList = getEmployeeByGroupId(s.getId());
            }
            responseVO.setEmployeeList(employeeInfoList);
            responseVO.setEmployeeCount(employeeInfoList.size());
            resList.add(responseVO);
        });
        // 修改分页数据
        result.setDataList(resList);
        result.setPageIndex(groupPager.getPageIndex());
        return result;
    }

    //勾选某组织，其下的所有组织及员工都相当于选中，若要只选其下的某些项，需要先取消选择该组织
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult selectEmployeeDetailPageByGroupId(SelectGroupPageRequestVO vo) {
        if (ObjectUtils.isEmpty(vo.getGroupId())) {
            throw new BaseException(BaseErrorCode.GROUP_ID_IS_NULL.getCode(), BaseErrorCode.GROUP_ID_IS_NULL.getMessage());
        }
        if (vo.getPageIndex() < 0) {
            throw new BaseException(BaseErrorCode.PAGE_INDEX_IS_NULL.getCode(), BaseErrorCode.PAGE_INDEX_IS_NULL.getMessage());
        }
        if (vo.getPageSize() <= 0) {
            throw new BaseException(BaseErrorCode.PAGE_SIZE_IS_NULL.getCode(), BaseErrorCode.PAGE_SIZE_IS_NULL.getMessage());
        }
        //根据用户组查询员工
        List<EmployeeInfo> employeeInfoList = sysEmployeeGroupDomain.pageEmployeeByGroupId(vo.getGroupId(), vo.getPageIndex(), vo.getPageSize());
        Integer count = sysEmployeeGroupDomain.pageEmployeeCountByGroupId(vo.getGroupId());
        Collections.synchronizedCollection(employeeInfoList).parallelStream().forEach(employeeInfo -> {
            List<List<OrgInfo>> orgInfoList = new ArrayList<>();
            List<Long> eachOrgIdList = sysEmployeeOrgDomain.selectOrgIdListByEmployeeId(employeeInfo.getEmployeeId()).stream().distinct().collect(Collectors.toList());
            Collections.synchronizedCollection(eachOrgIdList).parallelStream().forEach(eachOrgId -> {
                List<SysOrg> orgList = sysOrgDomain.selectOrgIdListRecursiveToRoot(eachOrgId);
                List<OrgInfo> orgInfos = new ArrayList<>();
                Collections.synchronizedCollection(orgList).parallelStream().forEach(sysOrg -> {
                    OrgInfo orgInfo = new OrgInfo();
                    orgInfo.setId(sysOrg.getId());
                    orgInfo.setName(sysOrg.getOrgName());
                    orgInfo.setParentId(sysOrg.getParentId());
                    orgInfos.add(orgInfo);
                });
                orgInfoList.add(orgInfos);
            });
            employeeInfo.setOrgInfoList(orgInfoList);
        });
        //list分页
        int pageSum = (count - 1) / vo.getPageSize() + 1;
        PagerEntity<EmployeeInfo> pagerEntity = new PagerEntity<>();
        pagerEntity.setDataList(employeeInfoList);
        pagerEntity.setTotal(count);
        pagerEntity.setPageIndex(vo.getPageIndex());
        pagerEntity.setPageSize(vo.getPageSize());
        pagerEntity.setTotalPages(pageSum);
        return BaseResult.buildSuccess(pagerEntity);
    }

    public BaseResult selectEmployeeByGroupId(@RequestParam("groupId") Long groupId) {
        if (ObjectUtils.isEmpty(groupId)) {
            return BaseResult.buildSuccess();
        }
        return BaseResult.buildSuccess(getEmployeeByGroupId(groupId));
    }

    private List<EmployeeInfo> getEmployeeByGroupId(Long groupId) {
        return sysEmployeeGroupDomain.selectEmployeeListByGroupCondition(groupId, null, null, null, null, null, null, null);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult selectGroupPageByEmployeeCondition(SelectGroupPageRequestVO vo) {
        // 1、检查参数合法性
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (vo.getPageIndex() < 0) {
            throw new BaseException(BaseErrorCode.PAGE_INDEX_IS_NULL.getCode(), BaseErrorCode.PAGE_INDEX_IS_NULL.getMessage());
        }
        if (vo.getPageSize() <= 0) {
            throw new BaseException(BaseErrorCode.PAGE_SIZE_IS_NULL.getCode(), BaseErrorCode.PAGE_SIZE_IS_NULL.getMessage());
        }
        if (vo.getPageSize() > 10) {
            throw new BaseException(GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getMsg());
        }

        // CMOS限定条件模糊时，只会传入employeeName参数，而实际其想支持employeeCode，因此统一增加searchKey，满足该条件
        String employeeName = vo.getEmployeeName();
        if (StringUtils.isNotEmpty(employeeName)) {
            vo.setSearchKey(employeeName);
            vo.setEmployeeName(null);
        }
        Set<Long> groupIds = sysGroupDomain.getGroupIdSetByEmployeeCondition(vo);
        // 3、通过人员组ID清单，分页查询人员组详情列表
        SysGroup sysGroup = new SysGroup();
        BeanUtils.copyProperties(vo, sysGroup);
        sysGroup.setGroupIdList(new ArrayList<>(groupIds));
        sysGroup.setEmployeeName(vo.getEmployeeName());
        sysGroup.setUserAccount(vo.getUserAccount());
        PagerEntity<SelectGroupPageResponseVO> result = pageSelect(sysGroup, vo.getPageIndex(), vo.getPageSize());
        return BaseResult.buildSuccess(result);
    }


    /**
     * 转换时间
     *
     * @param localDateTime 时间
     * @return 转换后的时间
     */
    private Date convertLocalDateTime(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }


    /**
     * 新增用户组
     *
     * @param sysGroupCreateRequestVO 入参
     * @return 新增结果
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult insert(SysGroupCreateRequestVO sysGroupCreateRequestVO) {
        this.addGroup(sysGroupCreateRequestVO);
        return BaseResult.buildSuccess();
    }

    /**
     * 新增用户组
     *
     * @param sysGroupCreateRequestVO 入参
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Long addGroup(SysGroupCreateRequestVO sysGroupCreateRequestVO) {
        String groupCode = sysGroupCreateRequestVO.getGroupCode();
        String groupName = sysGroupCreateRequestVO.getGroupName();
        if (ObjectUtils.isEmpty(groupCode) || groupCode.length() > 36) {
            throw new BaseException(SysGroupErrorCode.GROUP_CODE_IS_NULL_OR_OVER_SIZE.getCode(), SysGroupErrorCode.GROUP_CODE_IS_NULL_OR_OVER_SIZE.getMessage());
        }
        if (ObjectUtils.isEmpty(groupName) || groupName.length() > 64) {
            throw new BaseException(SysGroupErrorCode.GROUP_NAME_IS_NULL_OR_OVER_SIZE.getCode(), SysGroupErrorCode.GROUP_NAME_IS_NULL_OR_OVER_SIZE.getMessage());
        }
        // 校验编码和名称
        this.checkGroupInfo(groupCode, groupName);
        SysGroup sysGroup = new SysGroup();
        BeanUtils.copyProperties(sysGroupCreateRequestVO, sysGroup);
        sysGroup.setGroupState(SysGroupStateEnum.VALID.getValue());
        sysGroup.setUuid(UUID.randomUUID().toString().replace("-", ""));
        sysGroup.setCreator(sysGroupCreateRequestVO.getUserName());
        sysGroup.setModifier(sysGroupCreateRequestVO.getUserName());
        sysGroupDomain.insert(sysGroup);
        List<Long> employeeIdList = sysGroupCreateRequestVO.getEmployeeIdList();
        List<Long> orgIdList = sysGroupCreateRequestVO.getOrgIdList();
        //组织和单独勾选的员工分开处理
        if (!CollectionUtils.isEmpty(employeeIdList)) {
            this.batchAddOnlyEmployee(employeeIdList, sysGroup.getId(), sysGroupCreateRequestVO.getUserName());
        }
        if (!CollectionUtils.isEmpty(orgIdList)) {
            this.batchAddOrg(orgIdList, sysGroup.getId(), sysGroupCreateRequestVO.getUserName());
        }

        // 清理缓存
        sysUserCacheService.deleteUserFromCacheByGroupUpdate(sysGroup.getId());
        return sysGroup.getId();
    }

    /**
     * 更新用户组
     *
     * @param sysGroupUpdateRequestVO 入参
     * @return 更新结果
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult update(SysGroupUpdateRequestVO sysGroupUpdateRequestVO) {
        if (ObjectUtils.isEmpty(sysGroupUpdateRequestVO.getGroupId())) {
            throw new BaseException(BaseErrorCode.GROUP_ID_IS_NULL.getCode(), BaseErrorCode.GROUP_ID_IS_NULL.getMessage());
        }
        if (!ObjectUtils.isEmpty(sysGroupUpdateRequestVO.getGroupCode()) && sysGroupUpdateRequestVO.getGroupCode().length() > 36) {
            throw new BaseException(SysGroupErrorCode.GROUP_CODE_IS_NULL_OR_OVER_SIZE.getCode(), SysGroupErrorCode.GROUP_CODE_IS_NULL_OR_OVER_SIZE.getMessage());
        }
        if (!ObjectUtils.isEmpty(sysGroupUpdateRequestVO.getGroupName()) && sysGroupUpdateRequestVO.getGroupName().length() > 64) {
            throw new BaseException(SysGroupErrorCode.GROUP_NAME_IS_NULL_OR_OVER_SIZE.getCode(), SysGroupErrorCode.GROUP_NAME_IS_NULL_OR_OVER_SIZE.getMessage());
        }
        Long groupId = sysGroupUpdateRequestVO.getGroupId();
        String groupCode = sysGroupUpdateRequestVO.getGroupCode();
        String groupName = sysGroupUpdateRequestVO.getGroupName();
        List<Long> employeeIdList = sysGroupUpdateRequestVO.getEmployeeIdList();
        List<Long> orgIdList = sysGroupUpdateRequestVO.getOrgIdList();
        // 查询原来的用户组详情
        SysGroup oldSysGroup = sysGroupDomain.getById(groupId);
        if (oldSysGroup.getGroupCode().equals(groupCode)) {
            groupCode = null;
        }
        if (oldSysGroup.getGroupName().equals(groupName)) {
            groupName = null;
        }
        // 校验编码和名称
        this.checkGroupInfo(groupCode, groupName);
        // 更新信息
        SysGroup sysGroup = new SysGroup();
        sysGroup.setId(groupId);
        BeanUtils.copyProperties(sysGroupUpdateRequestVO, sysGroup);
        sysGroup.setModifier(sysGroupUpdateRequestVO.getUserName());
        LocalDateTime now = LocalDateTime.now();
        sysGroup.setGmtModified(now);
        sysGroupDomain.updateById(sysGroup);
        //关系表删除后新增
        SysEmployeeGroup sysEmployeeGroup = SysEmployeeGroup.builder().build();
        sysEmployeeGroup.setGroupId(groupId);
        sysEmployeeGroup.setIsDeleted(YesOrNo.Y.name());
        sysEmployeeGroup.setGmtModified(LocalDateTime.now());
        SysOrgGroup sysOrgGroup = SysOrgGroup.builder().build();
        sysOrgGroup.setGroupId(groupId);
        sysOrgGroup.setIsDeleted(YesOrNo.Y.name());
        sysOrgGroup.setGmtModified(LocalDateTime.now());
        if (null != groupId && groupId > 0) {
            sysEmployeeGroupDomain.updateByEmployeeIdGroupId(sysEmployeeGroup);
            sysOrgGroupDomain.updateByOrgIdGroupId(sysOrgGroup);
        }
        if (!CollectionUtils.isEmpty(employeeIdList)) {
            this.batchAddOnlyEmployee(employeeIdList, groupId, sysGroupUpdateRequestVO.getUserName());
        }
        if (!CollectionUtils.isEmpty(orgIdList)) {
            this.batchAddOrg(orgIdList, groupId, sysGroupUpdateRequestVO.getUserName());
        }

        // 清理缓存
        sysUserCacheService.deleteUserFromCacheByGroupUpdate(groupId);
        return BaseResult.buildSuccess();
    }

    /**
     * 批量删除用户组
     *
     * @param groupIdList 用户组列表
     * @return 删除结果
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult delete(List<Long> groupIdList) {
        // 检查参数合法性
        if (CollectionUtils.isEmpty(groupIdList)) {
            log.info("SysGroupServiceImpl delete groupIdList is null");
            return BaseResult.buildError("参数不能为空");
        }

        // 检查人员组是否还包含人员或组织
        List<SysGroup> groupList = sysGroupDomain.getListByIds(groupIdList);
        if (CollectionUtils.isEmpty(groupIdList)) {
            return BaseResult.buildError("用户组不存在");
        }
        List<SysEmployeeGroup> sysEmployeeGroupList = sysEmployeeGroupDomain.selectEmployeeGroupListByGroupIds(groupIdList, Constants.N);
        Map<Long, List<SysEmployeeGroup>> sysEmployeeGroupMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(sysEmployeeGroupList)) {
            sysEmployeeGroupList.forEach(item -> {
                if (sysEmployeeGroupMap.containsKey(item.getGroupId())) {
                    sysEmployeeGroupMap.get(item.getGroupId()).add(item);
                } else {
                    List<SysEmployeeGroup> tmpSysEmpGroupList = new ArrayList<>();
                    tmpSysEmpGroupList.add(item);
                    sysEmployeeGroupMap.put(item.getGroupId(), tmpSysEmpGroupList);
                }
            });
        }
        List<SysOrgGroup> sysOrgGroupList = sysOrgGroupDomain.selectOrgGroupListByGroupIds(groupIdList, Constants.N);
        Map<Long, List<SysOrgGroup>> sysOrgGroupMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(sysOrgGroupList)) {
            sysOrgGroupList.forEach(item -> {
                if (sysOrgGroupMap.containsKey(item.getGroupId())) {
                    sysOrgGroupMap.get(item.getGroupId()).add(item);
                } else {
                    List<SysOrgGroup> tmpSysOrgGroupList = new ArrayList<>();
                    tmpSysOrgGroupList.add(item);
                    sysOrgGroupMap.put(item.getGroupId(), tmpSysOrgGroupList);
                }
            });
        }
        Set<String> groupNameSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(sysEmployeeGroupMap) || !CollectionUtils.isEmpty(sysOrgGroupMap)) {
            groupList.forEach(item -> {
                boolean hasEmp = null != sysEmployeeGroupMap.get(item.getId()) && !sysEmployeeGroupMap.get(item.getId()).isEmpty();
                boolean hasOrg = null != sysOrgGroupMap.get(item.getId()) && !sysOrgGroupMap.get(item.getId()).isEmpty();
                if (hasEmp || hasOrg) {
                    groupNameSet.add(item.getGroupName());
                }
            });
        }
        if (!groupNameSet.isEmpty()) {
            String tipMsg = String.format("用户组 %s 包含有人员或组织，请先清理", groupNameSet);
            log.info("SysGroupServiceImpl.delete {}", tipMsg);
            return BaseResult.buildError(tipMsg);
        }

        // 执行逻辑删除
        SysGroup updateSysGroup = new SysGroup();
        updateSysGroup.setIsDeleted(Constants.Y);
        updateSysGroup.setGmtModified(LocalDateTime.now());
        XxlSsoUser xxlSsoUser = UserContextUtils.getCurrentUser();
        String currentUserName = null != xxlSsoUser ? xxlSsoUser.getUsername() : Constants.UNKNOW;
        updateSysGroup.setModifier(currentUserName);
        int iRtn = sysGroupDomain.updateDeleteFlagByGroupIds(updateSysGroup, groupIdList);
        log.info("sysGroupDomain.updateDeleteFlagByGroupIds rtn:{}", iRtn);

        // 说明：此处无需清理缓存，因为前面有限制条件，必须先解除与员工或组织的关系，而缓存全是基于用户员工维度存在的
        return BaseResult.buildSuccess();
    }

    /**
     * 删除用户组
     *
     * @param groupId 用户组标识
     */
    private void singleDelete(Long groupId) {
        SysGroup sysGroup = new SysGroup();
        sysGroup.setId(groupId);
        sysGroup.setIsDeleted(YesOrNo.Y.name());
        sysGroupDomain.updateById(sysGroup);
    }

    /**
     * 批量启用用户组
     *
     * @param vo 用户组列表
     * @return 启用结果
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult enable(List<Long> vo, String userName) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess();
        }
        vo.forEach(groupId -> this.singleUpdateGroupState(groupId, SysGroupStateEnum.VALID, userName));
        return BaseResult.buildSuccess();
    }

    /**
     * 更新用户组状态
     *
     * @param groupId   用户组标识
     * @param stateEnum 状态
     */
    private void singleUpdateGroupState(Long groupId, SysGroupStateEnum stateEnum, String userName) {
        SysGroup sysGroup = new SysGroup();
        sysGroup.setGroupState(stateEnum.getValue());
        sysGroup.setId(groupId);
        sysGroup.setModifier(userName);
        sysGroupDomain.updateById(sysGroup);
    }

    /**
     * 批量禁用用户组
     *
     * @param vo 用户组列表
     * @return 禁用结果
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult disable(List<Long> vo, String userName) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess();
        }
        vo.forEach(groupId -> this.singleUpdateGroupState(groupId, SysGroupStateEnum.INVALID, userName));
        return BaseResult.buildSuccess();
    }

    /**
     * 批量添加用户组和员工关系（仅包含单独勾选的员工）
     *
     * @param employeeIdList
     * @param groupId
     */
    private void batchAddOnlyEmployee(List<Long> employeeIdList, Long groupId, String userName) {
        if (null == employeeIdList) {
            employeeIdList = new ArrayList<>();
        }
        sysEmployeeGroupDomain.batchInsert(groupId, employeeIdList, userName);
    }

    /**
     * 批量添加用户组和组织关系
     *
     * @param orgIdList
     * @param groupId
     */
    private void batchAddOrg(List<Long> orgIdList, Long groupId, String userName) {
        if (null == orgIdList) {
            orgIdList = new ArrayList<>();
        }
        sysOrgGroupDomain.batchInsert(groupId, orgIdList, userName);
    }

    /**
     * 校验用户组信息
     *
     * @param groupCode 用户组编码
     * @param groupName 用户组名称
     */
    private void checkGroupInfo(String groupCode, String groupName) {
        // 校验用户组编码
        if (StringUtils.isNotEmpty(groupCode)) {
            SysGroup sysGroup = new SysGroup();
            sysGroup.setGroupCode(groupCode);
            Integer counts = sysGroupDomain.countByPara(sysGroup);
            if (counts > 0) {
                throw new BaseException(SysGroupErrorCode.GROUP_CODE_ALREADY_USED.getCode(), SysGroupErrorCode.GROUP_CODE_ALREADY_USED.getMessage());
            }
        }
        // 校验用户组名称
        if (StringUtils.isNotEmpty(groupName)) {
            SysGroup sysGroup = new SysGroup();
            sysGroup.setGroupName(groupName);
            Integer counts = sysGroupDomain.countByPara(sysGroup);
            if (counts > 0) {
                throw new BaseException(SysGroupErrorCode.GROUP_NAME_ALREADY_USED.getCode(), SysGroupErrorCode.GROUP_NAME_ALREADY_USED.getMessage());
            }
        }
    }

    /**
     * 通过人员组Id或Code查询人员组基本信息
     *
     * @param paramVO
     * @return
     */
    @Override
    public BaseResult<GroupBaseInfoResponseVO> getGroupBaseInfoByIdOrCode(GetGroupBaseInfoReqVO paramVO) {
        // 检查参数合法性
        if (null == paramVO) {
            return BaseResult.buildError("参数不能为空");
        }
        if (null == paramVO.getGroupId() && StringUtils.isEmpty(paramVO.getGroupCode())) {
            return BaseResult.buildError("人员组ID或人员组编码必填其一");
        }
        // 执行查询
        GroupBaseInfoResponseVO resultVO = sysGroupDomain.getGroupBaseInfoByIdOrCode(paramVO);
        return null != resultVO ? BaseResult.buildSuccess(resultVO) : BaseResult.buildError("没查到数据");
    }

    @Override
    public BaseResult getGroupBaseInfoByCode(String groupCode, String groupName) {
        if (ObjectUtils.isEmpty(groupCode) && ObjectUtils.isEmpty(groupName)) {
            return BaseResult.buildError("参数不能为空");
        }
        List<SelectGroupPageResponseVO> response = new ArrayList<>();
        List<SysGroup> groups = sysGroupDomain.getListCodeOrName(groupCode, groupName);
        if (CollectionUtils.isEmpty(groups)) {
            return BaseResult.buildSuccess(response);
        }
        Collections.synchronizedCollection(groups).parallelStream().forEach(item -> {
            SelectGroupPageResponseVO baseInfo = new SelectGroupPageResponseVO();
            baseInfo.setGroupCode(item.getGroupCode());
            baseInfo.setGroupName(item.getGroupName());
            baseInfo.setEmployeeList(getEmployeeByGroupId(item.getId()));
            response.add(baseInfo);
        });
        return BaseResult.buildSuccess(response);
    }

    @Override
    public BaseResult modifiedFromXbom(XbomReqParamVO vo) {
        if (StringUtils.isEmpty(vo.getGroupCode())) {
            return BaseResult.buildError("人员组编码参数不能为空！");
        }
        if (StringUtils.isEmpty(vo.getOperatorCode())) {
            return BaseResult.buildError("操作人编码参数不能为空！");
        }
        if (CollectionUtils.isEmpty(vo.getEmployeeCodes())) {
            return BaseResult.buildError("人员信息不能为空！");
        }
        if (!vo.getGroupCode().startsWith("XBOM_")) {
            return BaseResult.buildError("XBOM只能维护以XBOM_开头的人员组信息！");
        }
        GroupBaseInfoResponseVO groupBaseInfo = getGroupBaseInfo(vo.getGroupCode());
        if (ObjectUtils.isEmpty(groupBaseInfo)) {
            return BaseResult.buildError("人员组不存在或已经删除");
        }
        Set<Long> empIds = new HashSet<>();
        vo.getEmployeeCodes().forEach(item -> {
            SysEmployee employee = sysEmployeeDomain.selectByEmployeeCode(item);
            if (!ObjectUtils.isEmpty(employee)) {
                empIds.add(employee.getId());
            }
        });
        if (vo.getIsDelete()) {
            // 删除人员组员工关系
            empIds.forEach(item -> {
                SysEmployeeGroup sysEmployeeGroup = SysEmployeeGroup.builder().build();
                sysEmployeeGroup.setEmployeeId(item);
                sysEmployeeGroup.setGroupId(groupBaseInfo.getGroupId());
                sysEmployeeGroup.setIsDeleted(YesOrNo.Y.name());
                sysEmployeeGroupDomain.updateByEmployeeIdGroupId(sysEmployeeGroup);
            });
            // 删除人员组组织关
        } else {
            // 新增人员组
            empIds.forEach(item -> {
                SysEmployeeGroup employeeGroup = sysEmployeeGroupDomain.selectOneByEmployeeIdAndGroupId(item, groupBaseInfo.getGroupId());
                if (ObjectUtils.isEmpty(employeeGroup)) {
                    sysEmployeeGroupDomain.insert(groupBaseInfo.getGroupId(), item, vo.getOperatorCode());
                }
            });
        }
        return BaseResult.buildSuccess();
    }

    private GroupBaseInfoResponseVO getGroupBaseInfo(String groupCode) {
        GetGroupBaseInfoReqVO param = new GetGroupBaseInfoReqVO();
        param.setGroupCode(groupCode);
        param.setIsDeleted(YesOrNo.N.name());
        return sysGroupDomain.getGroupBaseInfoByIdOrCode(param);
    }

    @Override
    public BaseResult qryGroupDetailByGroupCodeFromXbom(String groupCode) {
        if (!groupCode.startsWith("XBOM_")) {
            return BaseResult.buildError("XBOM只能维护以XBOM_开头的人员组信息！");
        }
        GroupBaseInfoResponseVO groupBaseInfo = getGroupBaseInfo(groupCode);
        if (ObjectUtils.isEmpty(groupBaseInfo)) {
            return BaseResult.buildError("人员组不存在或已经删除");
        }
        XbomGroupInfoResVO xbomGroupInfoResVO = new XbomGroupInfoResVO();
        xbomGroupInfoResVO.setGroupId(groupBaseInfo.getGroupId());
        xbomGroupInfoResVO.setGroupCode(groupBaseInfo.getGroupCode());
        xbomGroupInfoResVO.setGroupName(groupBaseInfo.getGroupName());
        List<EmployeeGroupInfoVO> employeeGroupInfoVOS = sysEmployeeGroupDomain.selectEmployeeList(groupBaseInfo.getGroupId());
        List<XbomGroupEmpResVO> XbomGroupEmpResVO = employeeGroupInfoVOS.stream().map(item -> {
            XbomGroupEmpResVO xbomGroupEmpResVO = new XbomGroupEmpResVO();
            BeanUtils.copyProperties(item, xbomGroupEmpResVO);
            return xbomGroupEmpResVO;
        }).collect(Collectors.toList());
        xbomGroupInfoResVO.setGroupEmployees(XbomGroupEmpResVO);
        return BaseResult.buildSuccess(xbomGroupInfoResVO);
    }

    public BaseResult importExcel(MultipartFile file) {
        String[] strings = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        String fileType = strings[strings.length - 1];
        if (StringUtil.isEmpty(fileType) || !(fileType.equalsIgnoreCase(StringUtil.XLSX) || fileType.equalsIgnoreCase(StringUtil.XLS))) {
            return BaseResult.buildError(-1, "请上传xls或者xlsx类型文档。");
        }
        SysGroupListener listener = new SysGroupListener(sysGroupDomain);
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SysGroup.class, listener).sheet().doRead();
        } catch (Exception e) {
            log.error("group import error={}", e.getMessage());
            return BaseResult.buildError(-1, e.getMessage());
        }
        return BaseResult.buildSuccess();
    }
}
